/* 
 This file is part of the OdinMS Maple Story Server 
    Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>  
                       Matthias Butz <matze@odinms.de> 
                       Jan Christian Meyer <vimes@odinms.de> 

    This program is free software: you can redistribute it and/or modify 
    it under the terms of the GNU Affero General Public License version 3 
    as published by the Free Software Foundation. You may not use, modify 
    or distribute this program under any other version of the 
    GNU Affero General Public License. 

    This program is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    GNU Affero General Public License for more details. 

    You should have received a copy of the GNU Affero General Public License 
    along with this program.  If not, see <http://www.gnu.org/licenses/>.  

 * @author TheRamon 

    This is the item sort handler, which handles inventory sorting (red button next to X button) 
 */ 

package net.sf.odinms.net.channel.handler; 

import net.sf.odinms.client.MapleClient; 
import net.sf.odinms.net.AbstractMaplePacketHandler; 
import net.sf.odinms.client.MapleInventoryType; 
import net.sf.odinms.client.MapleInventory; 
import net.sf.odinms.server.MapleInventoryManipulator; 
import net.sf.odinms.tools.MaplePacketCreator; 
import net.sf.odinms.tools.data.input.SeekableLittleEndianAccessor; 

public class ItemSortHandler extends AbstractMaplePacketHandler { 
    @Override 
    public void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) { 
         slea.readInt(); 
         byte mode = slea.readByte(); 
         boolean sorted = false; 
         MapleInventoryType pInvType = MapleInventoryType.getByType(mode); 
         MapleInventory pInv = c.getPlayer().getInventory(pInvType);  

         while(!sorted) { 
            byte freeSlot = pInv.getNextFreeSlot(); 
            if (freeSlot != -1) { 
                byte itemSlot = -1; 
                for (byte i = (byte)(freeSlot+1); i <= 100; i++) { 
                    if (pInv.getItem(i) != null) { 
                        itemSlot = i; 
                        break; 
                    } 
                } 

                if (itemSlot <= 100 && itemSlot > 0) { 
                    MapleInventoryManipulator.move(c, pInvType, itemSlot, freeSlot); 
                } else { 
                    sorted = true; 
                } 
            } 
         } 
         c.getSession().write(MaplePacketCreator.enableActions()); 
    } 
}  